package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试锁
 *
 * @author dingwen
 * @date 2021/09/05
 */
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2,"tony").start();
        new Thread(testLock2,"lucy").start();
    }
}

class TestLock2 implements Runnable {
    int tickNum = 100;
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                if (tickNum > 0) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "拿到了第" + tickNum-- + "张票");
                } else {
                    break;
                }

            } finally {
                lock.unlock();
            }
        }

    }
}
